/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package extension.game.room.handler;

import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
import extension.game.database.Database;
import extension.game.room.Game;
import extension.game.room.Player;
import extension.game.room.RoomExtension;
import extension.game.zone.Flag;
import java.util.List;
import log.Debug;

/**
 *
 * @author daz
 */
public class OnUserGoneHandler extends BaseServerEventHandler {

    @Override
    public void handleServerEvent(ISFSEvent event) throws SFSException {
        User user = (User) event.getParameter(SFSEventParam.USER);
        Room room = (Room) event.getParameter(SFSEventParam.ROOM);
        Debug.d("user leave :" + user.getName());
        RoomExtension tienlenExtension = (RoomExtension) getParentExtension();
        Game game = tienlenExtension.getGame();
        Player[] listPlayers = game.getListPlayers();
        int leaveId = -1;
        for (int i = 0; i < listPlayers.length; i++) {
            if (listPlayers[i] != null) {
                if (listPlayers[i].getName().equals(user.getName())) {
                    leaveId = i;
                }
            }
        }

        if (user != null && leaveId >= 0) {
            long playerMoney = game.removePlayer(leaveId);
            if (!Debug.isDebug) {
                Database database = tienlenExtension.getDatabase();
                database.updateUserMoney(user.getName(), playerMoney);
                database.deleteMoneyQueue(tienlenExtension.getRoomPrefix(), user.getName());
            }
        }

        if (leaveId != -1) {
            tienlenExtension.getResponse().sendUserLeave(leaveId, game.getNumberPlayers(), game.getIsPlay(), user.getName());
            sendUpdate(tienlenExtension, user);
        }
    }

    private void sendUpdate(RoomExtension ext, User userExit) {
        Room room = ext.getParentRoom();
        String groupName = room.getGroupId();
        Room lobbyRoom = ext.getParentZone().getRoomByName("The Lobby");
        List<User> listSend = lobbyRoom.getUserList();
//        listSend.add(userExit);
        Debug.d("list send :" + listSend.toString());
        for (User u : listSend) {
            Debug.d("send update to :" + u.getName());
            String groupView = (String) u.getProperty(Flag.GROUP_NAME);
            if (groupView.equals(groupName)) {
                ext.getResponse().sendUpdateTable(room.getName(), ext.getGame().getNumberPlayings(), room.getGroupId(), ext.getGame().getBetMoney(), u);
            }
        }
    }
}
